import 'dart:ffi';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:webf/devtools.dart';
import 'package:webf/webf.dart';


import '../pojo/srtspan.dart';
import '../tools/srttools.dart';
import '../widget/doublenum_change_widget.dart';
import '../widget/num_change_widget.dart';

class StudyScreen extends StatefulWidget {
  StudyScreen({super.key, required this.mode, this.mp4Path, this.srtPath});

  // 运行模式
  int mode = 0;
  // mp4路径
  String? mp4Path;
  // srt路径
  String? srtPath;

  @override
  State<StudyScreen> createState() => _StudyScreenState();
}

class _StudyScreenState extends State<StudyScreen> {
  // 播放器
  late final player = Player();
  late final videoController = VideoController(player);

  // 字幕列表
  List<SrtSpan>? srts;

  // 当前字幕
  String curSubTitle = "";

  // 当前字幕索引
  int curIndex = -1;
  // 前一次检测字幕索引
  // int lastIndex = -1;
  // 跳转字幕索引
  int savedIndex = -1;

  // 最后有字幕索引
  int lastFindIndex = -1;

  bool showSubTitle = false;

  // 跳转字幕模式 跳过空闲片段
  bool jumpMode = false;
  DateTime? jumpDateTime;

  // 单句循环模式
  bool repeatMode = false;

  // 单句循环
  // int repeatIndex = -1;

  // 键盘监听
  FocusNode focusNode = FocusNode();

  String inputSubTitle = "";
  String inputLine = "";
  String inputWord = "";

  Map<int, bool> srtsOkMap = {};
  List<String> curSubTitleWords = <String>[];
  List<bool> checkList = <bool>[];
  // <bool> checkMap = {};
  List<String> curInputs = <String>[];
  int okCount = 0;

  // 最后位置
  Duration? lastPosition;

  int jumpAfterBlankSpanTime = 3000; // 无字幕后3秒，跳转
  int jumpCheckAfterSpanTime = 3000; // 跳转后3秒再次检测

  String lastSubTitle = "";
  DateTime blankDateTime = DateTime.now();

  // 播放开关
  bool playOn = true;
  // 等待秒数
  int repeatWaitTime = 3;
  // 重复次数
  int repeatQty = 3;

  // 播放速度
  double playRate = 1.0;

  late WebFController webController;

  @override
  void initState() {
    super.initState();

    // 播放视频
    playMp4();

    // 打开srt
    openSrt();

    // 监听视频播放状态
    player.stream.position.listen((Duration position) {
      // 刷新字幕
      findSubtitles(position.inMilliseconds);

      // 一个字幕快结束时停止
      if (curIndex != -1) {
        SrtSpan ss = srts![curIndex];
        if (srtsOkMap[curIndex] == null &&
            (position.inMilliseconds - ss.endTime).abs() < 100) {
          player.pause();
          savedIndex = curIndex;
          repeatOrConinue();
        }
      }
    });


  }

  void findSubtitles(int curTime) {
    // 1. 字幕还没加载完成,直接退出
    if (srts == null) return;

    int tmpIndex = -1;
    String tmpSubTitle = "";
    int startFind = srts!.length;

    if (lastFindIndex == -1) {
      // 还没加载过任何字幕，从头开始找
      startFind = 0;
    } else {
      // 加载过，先判断是否在之前范围内
      SrtSpan ss = srts![lastFindIndex];
      if (ss.startTime <= curTime) {
        if (ss.endTime >= curTime) {
          tmpIndex = lastFindIndex;
          tmpSubTitle = ss.content;
        } else {
          // 往后找
          startFind = curIndex + 1;
        }
      } else {
        // 从头找
        startFind = 0;
      }
    }

    for (int i = startFind; i < srts!.length; i++) {
      SrtSpan ss = srts![i];
      if (ss.startTime <= curTime) {
        if (ss.endTime >= curTime) {
          // 在范围内
          tmpIndex = i;
          tmpSubTitle = ss.content;
          lastFindIndex = i;
          break;
        }
      } else {
        // 结束查找
        break;
      }
    }
    // print("${tmpIndex}:${tmpSubTitle}");
    if (curIndex != tmpIndex) {
      setState(() {
        curIndex = tmpIndex;
        curSubTitle = tmpSubTitle;
        initRepeat();
      });
    }
  }

  Future<void> repeatOrConinue() async {
    print("隔${repeatWaitTime}秒跳转");
    Future.delayed(Duration(milliseconds: repeatWaitTime * 1000), () {
      // 如果已完成，则继续播放
      // 如果未完成，则跳回

      if(playOn) {
        if (srtsOkMap[savedIndex] == null) {
          SrtSpan srt = srts![savedIndex];
          player.seek(Duration(milliseconds: srt.startTime));
        }
        player.play();
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    webController = WebFController(
      context,
      devToolsService: ChromeDevToolsService(),
    );
    // controller.preload(WebFBundle.fromUrl('assets:assets/bundle.html'));
    // webController.preload(WebFBundle.fromUrl('https://m.baidu.com'));
  }

  @override
  Widget build(BuildContext context) {
    FocusScope.of(context).requestFocus(focusNode);
    FocusScope.of(context).autofocus(focusNode);

    return Scaffold(
      body: Column(
        children: [
          // 1. 播放器
          Expanded(
              child: buildMovieLine()),
          // 2. 字幕栏
          buildSubtitlePanel(),

          // 3. 工具栏
          buildToolbar(),
          // buildToolbarDebug(),
          buildProgressBar(),

          // 4. 输入栏
          buildInputPanel(),
        ],
      ),
    );
  }

  bool showRightPanel = false;


  buildMovieLine() {
    return Row(
      children: [
         Expanded(
           child: Video(
            controller: videoController,
                   ),
         ),
        Container(
          width: showRightPanel ? 0:300,
          color: Colors.black12,
          child: Container()
          // WebF(controller: webController)
        ),
        Container(
          width: 45,
          color: Colors.black,
          child: Column(children: [
            IconButton(onPressed: () {
              setState(() {
                showRightPanel = !showRightPanel;

                if(showRightPanel) {
                  // webViewController.go(uri: Uri.parse("https://m.baidu.com"));
                }

              });

            }, icon: Icon(Icons.hide_image)),
            IconButton(onPressed: () {}, icon: Icon(Icons.chrome_reader_mode)),
            IconButton(onPressed: () {}, icon: Icon(Icons.zoom_out_map)),
            IconButton(onPressed: () {}, icon: Icon(Icons.zoom_in_map)),
          ],),
        )
      ],
    );
  }

  // 创建字幕块
  // buildSubtitlePanel2() {
  //   return Container(
  //     height: 80,
  //     child: showSubTitle
  //         ? Text(
  //             textAlign: TextAlign.center,
  //             curSubTitle,
  //             style: TextStyle(
  //                 color: Colors.white,
  //                 fontSize: 40,
  //                 decoration: TextDecoration.none),
  //           )
  //         : Text(""),
  //     decoration: BoxDecoration(color: Colors.black),
  //     width: double.infinity,
  //   );
  // }



  buildToolbar() {
    return Container(
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          OutlinedButton(
              onPressed: () {
                op("play_or_pause");
              },
              child: Text(playOn ? "暂停" : "继续")),
          OutlinedButton(
              onPressed: () {
                op("prev_srt");
              },
              child: Text("上一句")),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(lastFindIndex != -1 ? "${lastFindIndex + 1}" : ""),
          ),
          OutlinedButton(
              onPressed: () {
                op("next_srt");
              },
              child: Text("下一句")),
          SizedBox(
            width: 20,
          ),
          // Text("重复:"),
          // Material(
          //     child: NumberInputWidget(
          //   onValueChanged: repeatQtyChange,
          //   num: 3,
          // )),
          // Text("次"),
          // SizedBox(
          //   width: 20,
          // ),
          Text("等待:"),
          Material(
              child: NumberInputWidget(
            onValueChanged: repeatWaitTimeChange,
            num: 3,
          )),
          Text("秒"),
          SizedBox(
            width: 20,
          ),
          Text("播放速度:"),
          Material(
              child: DoubleNumberInputWidget(
                onValueChanged: playSpeedChange,
                num: this.playRate,
              )),
          Text("倍速"),
          SizedBox(
            width: 20,
          ),
          OutlinedButton(
              onPressed: () {
                setState(() {
                  showSubTitle = !showSubTitle;
                });
              },
              child: Text(showSubTitle ? "隐藏字幕" : "显示字幕")),
          Text(srts == null
              ? ""
              : "已完成:${srtsOkMap.keys.length}/${srts!.length}"),
        ],
      ),
    );
  }

  buildToolbarDebug() {
    return Container(
        height: 40,
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          IconButton(
            onPressed: () {
              op("open_movie");
            },
            icon: Icon(Icons.file_open),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("open_srt");
            },
            icon: Icon(Icons.file_open_outlined),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("play_or_pause");
            },
            icon: Icon(Icons.play_arrow),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("prev_srt");
            },
            icon: Icon(Icons.replay),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("next_srt");
            },
            icon: Icon(Icons.refresh),
            color: Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op("switch_repeat");
            },
            icon: Icon(Icons.repeat_one),
            color: repeatMode ? Colors.green : Colors.grey,
          ),
          IconButton(
            onPressed: () {
              op(
                "switch_jump_mode",
              );
            },
            icon: Icon(Icons.redo),
            color: jumpMode ? Colors.green : Colors.grey,
          ),
          IconButton(
              onPressed: () {
                op("test1");
              },
              icon: Icon(Icons.abc)),
          IconButton(onPressed: () {}, icon: Icon(Icons.call_to_action)),
          IconButton(onPressed: () {}, icon: Icon(Icons.chrome_reader_mode)),
          IconButton(onPressed: () {}, icon: Icon(Icons.zoom_out_map)),
          IconButton(onPressed: () {}, icon: Icon(Icons.zoom_in_map)),
          Text(
            "${curIndex}",
            style: TextStyle(
                color: Colors.green,
                fontSize: 25,
                decoration: TextDecoration.none),
          ),
          IconButton(
              onPressed: () {
                op("request_focus");
              },
              icon: Icon(Icons.terminal)),
        ]));
  }

  void repeatWaitTimeChange(int t) {
    print("数字改变:${t}");
    this.repeatWaitTime = t;
  }

  Future<void> playSpeedChange(double n)
  async {
    this.playRate = n;
    await player.setRate(n);
  }

  void repeatQtyChange(int num) {
    print("数字改变:${num}");
    this.repeatQty = num;
  }


  buildInputPanel() {
    return Container(
      height: 180,
      child: Column(
        children: [
          Container(
              decoration: BoxDecoration(color: Colors.amberAccent),
              width: double.infinity,
              alignment: Alignment.center,
              height: 60,
              child: buildShow()),
          Container(
            decoration: BoxDecoration(color: Colors.lightBlueAccent),
            width: double.infinity,
            alignment: Alignment.center,
            height: 60,
            child: Text(
              inputLine,
              style: TextStyle(
                  fontSize: 36,
                  color: Colors.white,
                  decoration: TextDecoration.none),
            ),
          ),
          KeyboardListener(
            focusNode: focusNode,
            autofocus: true, // 要开启自动焦点
            onKeyEvent: (KeyEvent event) {
              if (event.runtimeType == KeyDownEvent) {
                print(event.character);
                print(event.logicalKey.keyLabel);
                print(event.physicalKey.debugName);
                if (event.logicalKey.keyLabel == "Enter" ||
                    event.physicalKey.debugName == "Space") {
                  setState(() {
                    inputLine = inputWord;
                    inputWord = "";
                    checkInputSubTitle();
                  });
                } else if (event.logicalKey.keyLabel == "Backspace") {
                  if (inputWord.length > 0) {
                    setState(() {
                      print(inputWord);
                      if (inputWord.length == 1) {
                        inputWord = "";
                      } else {
                        inputWord =
                            inputWord.substring(0, inputWord.length - 2);
                      }
                      print(inputWord);
                    });
                  }
                } else if (event.character != null) {
                  setState(() {
                    inputWord += event.character!;
                  });
                }
              }
            },
            child: Container(
              decoration: BoxDecoration(color: Colors.green),
              width: double.infinity,
              alignment: Alignment.center,
              height: 60,
              child: Text(
                inputWord,
                style: TextStyle(
                    fontSize: 36,
                    color: Colors.white,
                    decoration: TextDecoration.none),
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildSubtitlePanel() {
    return Container(
      height: 80,
      alignment: Alignment.center,
      child: showSubTitle
          ? buildShow1()
          : Text(""),
      decoration: BoxDecoration(color: Colors.black),
      width: double.infinity,
    );
  }

  final TextStyle textStyle3 = const TextStyle(
    fontSize: 36,
    color: Colors.white,
  );
  buildShow1()
  {
    List<TextSpan> spans = <TextSpan>[];
    for (int i = 0; i < curSubTitleWords.length; i++) {
      TextSpan ts = TextSpan(text: curSubTitleWords[i], style: textStyle3,recognizer: TapGestureRecognizer()
        ..onTap = () {
          // 点击事件的处理逻辑
          print('TextSpan 被点击了:'+curSubTitleWords[i]);
        },
      );
      spans.add(ts);
    }
    InlineSpan span = TextSpan(children: spans);
    return Text.rich(span);
  }

  buildShow() {
    List<TextSpan> spans = <TextSpan>[];
    for (int i = 0; i < curSubTitleWords.length; i++) {
      TextSpan ts;
      if (checkList[i] == true) {
        ts = TextSpan(text: curSubTitleWords[i], style: textStyle1);
      } else {
        ts = TextSpan(text: curSubTitleWords[i], style: textStyle2);
      }
      // TextSpan ts2 = TextSpan(text: " ", style: blankStyle);
      spans.add(ts);
      // spans.add(ts2);
    }
    InlineSpan span = TextSpan(children: spans);
    return Text.rich(span);
  }

  final TextStyle textStyle1 = const TextStyle(
    // color: Colors.amberAccent,
    fontSize: 36,
    color: Colors.green,
  );

  final TextStyle textStyle2 = const TextStyle(
      // color: Colors.black,
      fontSize: 36,
      color: Colors.amberAccent,
      decoration: TextDecoration.underline,
      decorationStyle: TextDecorationStyle.solid,
      decorationThickness: 1,
      decorationColor: Colors.white);

  final TextStyle blankStyle = const TextStyle(
      decoration: TextDecoration.none, decorationColor: Colors.blue);

  String testPath = "";
  Future<void> op(String s) async {
    print("op:" + s);
    switch (s) {
      case "play_or_pause":
        print("暂停或继续播放");
        playOn = !playOn;
        if (playOn) {
          player.play();
        } else {
          player.pause();
        }
        setState(() {});
        break;
      case "prev_srt":
        prevSrt();
        break;
      case "next_srt":
        nextSrt();
        break;
    }
  }

  Future<void> openSrt() async {
    // File file = File("/Users/qiang/Downloads/unity2story.srt");
    File file = File(widget.srtPath!);
    String content = await file.readAsString();
    print("读取到内容:" + content);
    srts = SrtTools.handleSrtContent(content);
  }

  void playMp4() {
    print("播放器视频:");
    print(widget.mp4Path!);
    player.open(Media(widget.mp4Path!));
  }

  buildProgressBar() {
    return Container(
      width: double.infinity,
      height: 20,
      decoration: BoxDecoration(color: Colors.grey),
      child: Flex(
        direction: Axis.horizontal,
        children: buildProgressBarDivs(),
      ),
    );
  }

  buildProgressBarDivs() {
    List<Widget> list = [];
    if (srts == null) {
      Widget w = Expanded(
        flex: 1,
        child: Container(
          height: 28.0,
          color: Colors.white10,
        ),
      );
      list.add(w);
    } else {
      for (int i = 0; i < srts!.length; i++) {
        Widget w = Expanded(
          flex: 1,
          child: GestureDetector(
            onTap: () {
              jumpTo(i);
            },
            child: Container(
              height: 28.0,
              color: srtsOkMap[i] == null ? Colors.grey : Colors.green,
              margin: EdgeInsets.all(2),
              alignment: Alignment.center,
              child: Container(
                  alignment: Alignment.center,
                  width: 20,
                  color: curIndex == i
                      ? Colors.red
                      : (srtsOkMap[i] == null ? Colors.grey : Colors.green),
                  child: Text(
                    "${i + 1}",
                    style: TextStyle(color: Colors.white),
                  )),
            ),
          ),
        );
        list.add(w);
      }
    }
    return list;
  }

  void prevSrt() {
    if (srts == null) return;
    print("curIndex = ${curIndex}");
    int jumpIndex = -1;
    if (curIndex != -1) {
      jumpIndex = curIndex - 1;
    } else {
      jumpIndex = lastFindIndex;
    }
    if (jumpIndex != -1) {
      player.seek(Duration(milliseconds: srts![jumpIndex].startTime));
    }
  }

  void nextSrt() {
    if (srts == null) return;
    print("curIndex = ${curIndex}");
    int jumpIndex = -1;
    if (curIndex != -1) {
      jumpIndex = curIndex + 1;
    } else {
      jumpIndex = lastFindIndex + 1;
    }
    if (jumpIndex != srts!.length) {
      player.seek(Duration(milliseconds: srts![jumpIndex].startTime));
    }
  }

  // 字幕处理
  void initRepeat() {
    if (curIndex == -1) return;
    String tmp1 = srts![curIndex].content!;
    curSubTitleWords = SrtTools.handleAll(tmp1);
    checkList = [];
    List<String> symbols = [",", ".", "!", "?", " "];
    for (int i = 0; i < curSubTitleWords.length; i++) {
      if (symbols.contains(curSubTitleWords[i])) {
        checkList.add(true);
      } else {
        checkList.add(false);
      }
    }
    print(curSubTitleWords);
    print(checkList);
  }

  void checkInputSubTitle() {
    for (int i = 0; i < curSubTitleWords.length; i++) {
      if (checkList[i] == false) {
        String tmp = curSubTitleWords[i];
        // 不比较单引号
        tmp = tmp.replaceAll("'", "");
        inputLine = inputLine.replaceAll("'", "");
        if (tmp.toLowerCase() == inputLine.toLowerCase()) {
          checkList[i] = true;
          break;
        }
      }
    }

    bool ok = true;
    for (int i = 0; i < curSubTitleWords.length; i++) {
      if (checkList[i] == false) {
        ok = false;
      }
    }
    if (ok) {
      srtsOkMap[curIndex] = true;
    }
  }

  void jumpTo(int i) {
    SrtSpan srt = srts![i];
    player.seek(Duration(milliseconds: srt.startTime));
  }


}
